package com.dal.elasticsearch.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName RestClientConfig
 * @Author jian
 * @Date 2:52 PM 2022/10/9
 **/
@Configuration
public class RestClientConfig{

    private static String ES_URL = "127.0.0.1:9200";

    @Bean
    RestHighLevelClient configRestHighLevelClient() throws Exception {

        String[] esUrlArr = ES_URL.split(",");

        List<HttpHost> httpHosts = new ArrayList<>();
        for(String es : esUrlArr){
            String[] esUrlPort = es.split(":");
            httpHosts.add(new HttpHost(esUrlPort[0], Integer.parseInt(esUrlPort[1]), "http"));
        }

        return new RestHighLevelClient(
                RestClient.builder(httpHosts.toArray(new HttpHost[0]))
        );
    }
}
